<template>
  <div class="comments">
    <div class="main">
      <div class="header">
        <el-form :inline="true">
          <el-form-item label="用户名">
            <el-input
              placeholder="请输入搜索的用户名"
              v-model="findCommenQuery.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input placeholder="请输入用户邮箱" v-model="findCommenQuery.userEmail"></el-input>
          </el-form-item>
          <el-form-item label="类别">
            <el-select placeholder="请选择评论类别" v-model="findCommenQuery.category">
              <el-option label="文章" value="1"></el-option>
              <el-option label="动态" value="2"></el-option>
              <el-option label="项目" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select placeholder="请选择状态" v-model="findCommenQuery.status">
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="评论时间">
            <el-date-picker
              v-model="findCommenQuery.createTime"
              type="datetime"
              placeholder="请选择"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="findComments">查询</el-button>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch">
              <el-icon><Minus /></el-icon>
              <span>批量删除</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body" v-if="commentsList.length > 0">
        <el-table :data="commentsList" @selection-change="handleSelectionDelete">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="头像" width="120" prop="headerUrl">
            <template #default="scope">
              <el-avatar :src="scope.row.headerUrl"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="用户名" width="120" prop="username"></el-table-column>
          <el-table-column
            label="用户邮箱"
            prop="userEmail"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="评论内容" show-overflow-tooltip prop="content"></el-table-column>
          <el-table-column label="类别" prop="category" width="80">
            <template #default="scope">
              <span>{{ computedCategory(scope.row.category) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="80">
            <template #default="scope">
              <span
                :class="scope.row.status === 0 ? 'blue' : 'red'"
                @click="updateStatus(scope.row.status === 0 ? 1 : 0, scope.row.id)"
                >{{ scope.row.status === 0 ? '启用' : '禁用' }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="回复状态" prop="replyStatus" width="80">
            <template #default="scope">
              <span :class="scope.row.replyStatus === 0 ? 'red' : 'blue'">{{
                scope.row.replyStatus === 0 ? '未回复' : '已回复'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="修改时间"
            prop="updateTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" width="125" class="operate">
            <template #default="scope">
              <span
                style="color: #f56c6c; margin-right: 7px; cursor: pointer; font-weight: 600"
                @click="deleteById(scope.row.id)"
                >删除</span
              >
              <span
                style="color: #75c553; margin-right: 7px; cursor: pointer; font-weight: 600"
                @click="getCommentById(scope.row.id)"
                >查看</span
              >
              <span
                style="color: #409eff; cursor: pointer; font-weight: 600"
                @click="replyComment(scope.row.id, scope.row.replyStatus)"
                >回复</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else></el-empty>
      <div class="page">
        <el-pagination
          :total="total"
          v-model:current-page="findCommenQuery.page"
          v-model:page-size="findCommenQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
      <!-- 评论详细信息 -->
      <el-dialog v-model="dialogVisible" width="700">
        <el-descriptions title="评论详细信息" direction="vertical" border>
          <el-descriptions-item :rowspan="2" :width="120" label="头像" align="center">
            <el-image style="width: 100px; height: 100px" :src="detailInfo.headerUrl"></el-image>
          </el-descriptions-item>
          <el-descriptions-item label="用户名">{{ detailInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ detailInfo.userEmail }}</el-descriptions-item>
          <el-descriptions-item label="评论时间">{{ detailInfo.createTime }}</el-descriptions-item>
          <el-descriptions-item label="评论类别">{{
            computedCategory(detailInfo.category)
          }}</el-descriptions-item>
          <el-descriptions-item label="评论内容" width="150">
            {{ detailInfo.content }}
          </el-descriptions-item>
          <el-descriptions-item label="回复内容">{{
            detailInfo.replyContent
          }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { Minus } from '@element-plus/icons-vue'
import {
  deleteBaatchService,
  getByIdService,
  getCommentListService,
  replyCommentService,
  updateStatusService,
} from '@/api/Comment'
import { ElMessage, ElMessageBox } from 'element-plus'

// 传递参数
const findCommenQuery = ref({
  page: 1,
  pageSize: 9,
  username: '',
  userEmail: '',
  category: null,
  status: null,
  createTime: '',
})

// 接收返回数据
const total = ref(null)
const commentsList = ref([])

const findComments = () => {
  getCommensList(findCommenQuery.value)
}
const replace = () => {
  findCommenQuery.value = {
    page: 1,
    pageSize: 9,
    username: '',
    userEmail: '',
    category: null,
    status: null,
    createTime: '',
  }
  getCommensList({
    page: 1,
    pageSize: 9,
    username: '',
    userEmail: '',
    category: null,
    status: null,
    createTime: '',
  })
}

/**
 * 查看评论详细信息
 */
const dialogVisible = ref(false) // 控制对话框希纳是隐藏
const detailInfo = ref({})
const getCommentById = async (id) => {
  dialogVisible.value = true
  const { data } = await getByIdService(id)
  detailInfo.value = data
}

/**
 * 修改评论状态
 * @param status
 * @param id
 */
const updateStatus = (status, id) => {
  updateStatusService(status, id).then(() => {
    getCommensList(findCommenQuery.value)
  })
}

const commentIds = ref([])
/**
 * 删除评论
 * @param id
 */
const deleteById = (id) => {
  ElMessageBox.confirm('你确认删除该条评论数据吗?', 'Warning', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(() => {
      commentIds.value.push(id)
      console.log(commentIds.value)
      deleteBaatchService(commentIds.value).then(() => {
        commentIds.value = commentIds.value.filter((item) => item !== id)
        getCommensList(findCommenQuery.value)
      })
    })
    .catch(() => {
      ElMessage.success('取消删除成功')
    })
}
// 复选框
const handleSelectionDelete = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  commentIds.value = []
  obj.forEach((item) => {
    commentIds.value.push(item.id)
  })
}
// 批量删除
const deleteBatch = () => {
  if (commentIds.value.length === 0) {
    ElMessage.error('未选中任何数据')
  } else {
    ElMessageBox.confirm(`你确认删除这${commentIds.value.length}条数据吗?`, 'Warning', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    })
      .then(() => {
        deleteBaatchService(commentIds.value).then(() => {
          commentIds.value = []
          getCommensList(findCommenQuery.value)
        })
      })
      .catch(() => {
        ElMessage.success('取消删除')
      })
  }
}

/**
 * 回复评论
 */
const replyComment = (id, replyStatus) => {
  if (replyStatus === 1) {
    ElMessage.warning('该评论已回复')
  } else {
    ElMessageBox.prompt('请输入回复内容', 'Tip', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '回复内容不能为空',
    })
      .then((value) => {
        console.log('文章id:', id, '回复内容:', value.value)
        replyCommentService(id, value.value).then(() => {
          getCommensList(findCommenQuery.value)
        })
      })
      .catch(() => {
        ElMessage({
          type: 'success',
          message: '取消回复',
        })
      })
  }
}

// 分页查询
const handlePageChange = (page) => {
  findCommenQuery.value.page = page
  getCommensList(findCommenQuery.value)
}
const handlePageSizeChange = (pageSize) => {
  findCommenQuery.value.pageSize = pageSize
  getCommensList(findCommenQuery.value)
}
/**
 * 计算类别显示字段
 */
const computedCategory = (category) => {
  if (category === 1) {
    return '文章'
  }
  if (category === 2) {
    return '动态'
  }
  if (category === 3) {
    return '项目'
  }
}

/**
 * 查询所有评论数据
 * @param query
 */
const getCommensList = async (query) => {
  const { data } = await getCommentListService(query)
  total.value = data.total
  commentsList.value = data.records
}
onMounted(() => {
  getCommensList(findCommenQuery.value)
})
</script>

<style lang="scss" scoped>
.comments {
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    .header {
      margin-top: 15px;

      :deep(.el-select__wrapper) {
        width: 150px;
      }
      :deep(.el-date-editor) {
        width: 200px;
      }
    }

    .page {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

.blue {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
::v-deep.el-table .cell {
  text-align: center !important;
}
</style>